package com.hhh.petadopt.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hhh.petadopt.pojo.User;
import com.hhh.petadopt.service.LoginService;
import com.hhh.petadopt.utils.CookieUtils;
import com.hhh.petadopt.utils.E3Result;

/**
 * 登录
 * @author 杜镇声声
 *
 */
@Controller
public class Logincontroller {
	
	@Autowired
	private LoginService loginService;
	
	//显示登录页面
	@RequestMapping(value="/login.html")
	public String showLogin(String redirect,Model model) {
		model.addAttribute("redirect", redirect);
		return "login";
	}
	
	//登录
	@RequestMapping(value="/user/login",method=RequestMethod.POST)
	@ResponseBody
	public E3Result login(User user,HttpServletRequest request,HttpServletResponse response) {
		E3Result e3Result  = loginService.userLogin(user);
		
		//判断是否登录成功
		if(e3Result.getStatus() == 200) {
			String token = e3Result.getData().toString();
			//如果登录成功需要把token写入cookie
			CookieUtils.setCookie(request, response, "token", token);
		}
		
		//返回结果
		return e3Result;
	}

}
